<template>
  <div class="exchange-info">
    <el-form ref="formRef" class="exchange-form" label-width="80px" :model="form" inline>
      <el-form-item label="交易类型" prop="type" :required="!disabled">
        <el-select
          v-model="form.type"
          :disabled="disabled"
          placeholder="请选择"
          @change="handleChange"
        >
          <el-option
            v-for="(item, index) in EXCHANGE_TYPE_LIST"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="disabled" label="交易时间" prop="count">
        {{ dayjs(Number(form.createTime)).format(TIME_FORMAT) }}
      </el-form-item>

      <el-form-item label="交易数量" prop="count" :required="!disabled">
        <el-input v-model="form.count" :disabled="disabled" @change="handleChange"></el-input>
      </el-form-item>

      <el-form-item label="交易单价" prop="price" :required="!disabled">
        <el-input v-model="form.price" :disabled="disabled" @change="handleChange"></el-input>
      </el-form-item>

      <el-form-item v-if="!disabled || form.remarks" label="备注" prop="remarks">
        <el-input v-model="form.remarks" :disabled="disabled" />
      </el-form-item>
    </el-form>

    <div class="title" v-if="!disabled">更新后:</div>
    <el-form inline v-if="!disabled">
      <el-form-item label="持仓市值:" prop="type">
        <div class="update-info">
          <span class="before">{{ info?.holdValue || 0 }}</span>
          <span class="icon">-></span>
          <span class="latest">{{ newHoldValue }}</span>
        </div>
      </el-form-item>

      <el-form-item label="持仓数量" prop="count">
        <div class="update-info">
          <span class="before">{{ info?.holdNum || 0 }}</span>
          <span class="icon">-></span>
          <span class="latest">{{ newHoldNum }}</span>
        </div>
      </el-form-item>

      <el-form-item label="持仓单价" prop="count">
        <div class="update-info">
          <span class="before">{{ info?.holdPrice || 0 }}</span>
          <span class="icon">-></span>
          <span class="latest">{{ newHoldPrice }}</span>
        </div>
      </el-form-item>
      <el-form-item label="持仓收益" prop="count">
        <div class="update-info">
          <span class="before">{{ info?.holdEarnings || 0 }}</span>
          <span class="icon">-></span>
          <span class="latest">{{ newHoldEarnings }}</span>
        </div>
      </el-form-item>
      <el-form-item label="持仓收益率" prop="count">
        <div class="update-info">
          <span class="before">{{ info?.holdEarningsPercent || 0 }}</span>
          <span class="icon">-></span>
          <span class="latest">{{ newHoldEarningsPercent }}</span>
        </div>
      </el-form-item>
    </el-form>
    <div v-if="!disabled" class="btn-area">
      <el-button @click="emit('close')">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { EXCHANGE_TYPE_LIST } from './model'
import { useList } from '@/hooks/useList'
import { useLatestPrice } from './useLatestPrice'
import dayjs from 'dayjs'
import { TIME_FORMAT } from '@/utils/time'
import type { HoldItem } from '@/indexDB/initHold'
import type { ExchangeItem } from '@/indexDB/initExchange'

const emit = defineEmits(['close', 'refresh'])
const props = defineProps<{
  info: HoldItem
  updateHold?: (form: HoldItem) => void
  disabled?: boolean
  record?: ExchangeItem
}>()

const form = ref<ExchangeItem>({
  type: 'buy',
  holdId: props.info.id,
  ...props.record
})

const { holdValue, holdNum, holdPrice, holdEarnings, holdEarningsPercent } = props.info

const newHoldValue = ref(holdValue || 0)
const newHoldNum = ref(holdNum || 0)
const newHoldPrice = ref(holdPrice || 0)
const newHoldEarnings = ref(holdEarnings || 0)
const newHoldEarningsPercent = ref(holdEarningsPercent || '0%')

const handleChange = () => {
  const { count = 0, price = 0, type } = form.value
  const oldCost = +(holdNum * holdPrice).toFixed(4)
  let newCostAll = 0
  if (type === 'buy') {
    newHoldNum.value = +(Number(holdNum) + Number(count)).toFixed(4)
    newCostAll = +(oldCost + price * count).toFixed(4)
  } else {
    newHoldNum.value = +(holdNum - count).toFixed(4)
    newCostAll = +(oldCost - price * count).toFixed(4)
  }
  if (!newHoldNum.value) {
    // 清仓了
    newHoldPrice.value = 0
    // 原来的数量乘以差价
    newHoldEarnings.value = +(holdNum * (price - holdPrice)).toFixed(4)
    newHoldEarningsPercent.value = (((price - holdPrice) / holdPrice) * 100).toFixed(2) + '%'
  } else {
    newHoldValue.value = +(newHoldNum.value * price).toFixed(4)
    newHoldPrice.value = +(newCostAll / newHoldNum.value).toFixed(4)
    newHoldEarnings.value = +((price - newHoldPrice.value) * holdNum).toFixed(4)

    newHoldEarningsPercent.value =
      (((price - newHoldPrice.value) / newHoldPrice.value) * 100).toFixed(4) + '%'
  }
}
const { handleAdd } = useList<ExchangeItem>({
  listKey: 'exchangeList'
})
const formRef = ref()
const handleConfirm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      form.value.createTime = new Date().getTime() + ''
      handleAdd(form.value)
      const newHoldItem = {
        ...props.info,
        holdNum: newHoldNum.value,
        holdPrice: newHoldPrice.value,
        holdValue: newHoldValue.value,
        holdEarnings: newHoldEarnings.value,
        holdEarningsPercent: newHoldEarningsPercent.value
      }
      props.updateHold?.(newHoldItem)
      useLatestPrice(newHoldItem, props.updateHold!)
      emit('close')
      emit('refresh')
    }
  })
}
</script>

<style lang="scss" scoped>
.exchange-info {
  .exchange-form {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
  }
  .title {
    margin-bottom: 10px;
    font-size: 26px;
    font-weight: 400;
  }
  .btn-area {
    text-align: end;
  }
  .update-info {
    display: flex;
    align-items: center;
    .icon {
      margin: 0 5px;
    }
    .latest {
      color: red;
    }
  }
}
</style>
